package servlet;

import com.alibaba.fastjson.JSON;
import entity.Employee;
import service.EmployeeServiceDao;
import service.Impl.EmployeeServiceDaoImpl;
import util.DateUtil;
import util.FileUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@WebServlet("/employee")
@MultipartConfig    //提供文件上传功能
public class findEmployeeByName extends HttpServlet {
    private EmployeeServiceDao employeeServiceDao = new EmployeeServiceDaoImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //获取参数 判断List add update delete
        String method = req.getParameter("method") == null ? "" : req.getParameter("method");
        switch (method) {
            case "list":
                list(req, resp);
                break;
            case "add":
                add(req, resp);
                break;
            case "edit":
                edit(req, resp);
                break;
            case "update":
                update(req, resp);
                break;
            case "delete":
                delete(req, resp);
                break;
        }
    }
    protected void edit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取员工ID
        int empId = Integer.parseInt(req.getParameter("id"));
        Employee employee = employeeServiceDao.getById(empId);
        req.setAttribute("employee", employee);
        req.getRequestDispatcher("/updateEmp.jsp").forward(req, resp);
    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取员工ID
        int empId = Integer.parseInt(req.getParameter("id"));

        // 2. 获取表单提交的新数据
        String name = req.getParameter("empName");
        String password = req.getParameter("password");
        String birthdayStr = req.getParameter("birthday");
        String salary = req.getParameter("salary");
        String depIdStr = req.getParameter("depId");
        String startStr = req.getParameter("start");

        // 3. 获取头像文件和原头像路径
        Part part = req.getPart("imgUrl");
        String oldImage = req.getParameter("oldImage");

        // 4. 处理头像上传
        String imagePath = oldImage;
        if (part != null && part.getSize() > 0) {
            imagePath = FileUtil.uploadFile(req, part);
            // 这里可以添加删除旧头像的逻辑
            // FileUtil.deleteFile(req, oldImage);
        }

        // 5. 构建Employee对象
        Employee employee = new Employee();
        employee.setId(empId);
        employee.setName(name);

        // 处理密码：为空则不更新
        if (password != null && !password.trim().isEmpty()) {
            employee.setPassword(password);
        } else {
            Employee oldEmployee = employeeServiceDao.getById(empId);
            employee.setPassword(oldEmployee.getPassword());
        }

        employee.setImage(imagePath);
        employee.setBirthday(DateUtil.formatDate(DateUtil.parseDate(birthdayStr)));
        employee.setSalary(salary);
        employee.setDepId(Integer.parseInt(depIdStr));
        employee.setStart(Integer.parseInt(startStr));
        employee.setUpdateTime(DateUtil.formatDateTime(new Date())); // 更新时间

        // 6. 执行更新
        int num = employeeServiceDao.update(employee);

        // 7. 跳转页面
        if (num > 0) {
            resp.sendRedirect(req.getContextPath() + "/emp.jsp");
        } else {
            resp.getWriter().write("更新失败，请稍后重试！");
        }
    }

    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //员工姓名
        String empName = req.getParameter("empName");
        List<Employee> employeeList = employeeServiceDao.findByName(empName);
        //将数据转成json
        String json = JSON.toJSONString(employeeList);
        resp.getWriter().write(json);

    }

    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端参数
        String name = req.getParameter("empName"); // 员工姓名
        String password = req.getParameter("password"); // 密码
        String birthdayStr = req.getParameter("birthday"); // 生日（前端传递格式：yyyy-MM-dd）
        String salary = req.getParameter("salary"); // 工资
        String depIdStr = req.getParameter("depId"); // 部门ID
//        Part imagePart = req.getPart("imgUrl"); // 头像文件
        //获取part对象
        Part part = req.getPart("imgUrl");
        String path = FileUtil.uploadFile(req, part);

        Employee employee = new Employee();
        employee.setName(name);
        employee.setPassword(password); // 实际项目中建议加密存储
        employee.setImage(path); // 头像路径（对应实体类的image字段）
        // 生日：String类型，直接存储格式化后的字符串
        employee.setBirthday(DateUtil.formatDate(DateUtil.parseDate(birthdayStr)));
        employee.setSalary(salary);
        employee.setDepId(Integer.parseInt(depIdStr)); // 部门ID（int类型）
        // 创建时间和更新时间：当前时间，转成字符串存储
        String currentTime = DateUtil.formatDateTime(new Date());
        employee.setCreateTime(currentTime);
        employee.setUpdateTime(currentTime);
        // start字段（如果前端有传递则设置，否则默认0）
        String startStr = req.getParameter("start");
        employee.setStart(startStr != null ? Integer.parseInt(startStr) : 0);
        boolean isSuccess = employeeServiceDao.insert(employee) >0 ? true : false ;
        if (isSuccess) {
            resp.sendRedirect(req.getContextPath() + "/emp.jsp");
        }
    }
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取要删除的员工ID
        int empId = Integer.parseInt(req.getParameter("id"));

        // 2. 调用Service层执行删除操作
        int num = employeeServiceDao.delete(empId);

        // 3. 根据删除结果响应给客户端
        if (num > 0) {
            // 删除成功，重定向回员工列表页面
            resp.sendRedirect("/emp.jsp");
        } else {
            // 删除失败，给用户提示
            resp.getWriter().write("删除失败，请稍后重试！");
        }
    }
}